/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.century.sjt.EMChat.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.EMChat.db.UserDao;
import com.century.sjt.domain.InviteMessage;
import com.century.sjt.domain.InviteMessage.InviteMesageStatus;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.easemob.chat.EMChatManager;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.utils.EaseCommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewFriendsMsgAdapter extends ArrayAdapter<InviteMessage> {

	private Context context;
	private InviteMessgeDao messgeDao;
	private RequestQueue mQueue;
	final Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
	final List<InviteMessage> mDataList;

	public NewFriendsMsgAdapter(Context context, int textViewResourceId, List<InviteMessage> objects, RequestQueue mQueqe) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.mDataList=objects;
		messgeDao = new InviteMessgeDao(context);
		this.mQueue = mQueqe;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(context, R.layout.em_row_invite_msg, null);
			holder.avator = (ImageView) convertView.findViewById(R.id.avatar);
			holder.reason = (TextView) convertView.findViewById(R.id.message);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.status = (Button) convertView.findViewById(R.id.user_state);
			holder.status2 = (Button) convertView.findViewById(R.id.user_state2);
			holder.groupContainer = (LinearLayout) convertView.findViewById(R.id.ll_group);
			holder.groupname = (TextView) convertView.findViewById(R.id.tv_groupName);
			// holder.time = (TextView) convertView.findViewById(R.id.time);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String str1 = context.getResources().getString(R.string.Has_agreed_to_your_friend_request);
		String str2 = context.getResources().getString(R.string.agree);
		
		String str3 = context.getResources().getString(R.string.Request_to_add_you_as_a_friend);
		String str4 = context.getResources().getString(R.string.Apply_to_the_group_of);
		String str5 = context.getResources().getString(R.string.Has_agreed_to);
		String str6 = context.getResources().getString(R.string.Has_refused_to);
		String str7 = context.getResources().getString(R.string.error_be_refuse);
		final InviteMessage msg = getItem(position);

//		Log.e("msg",msg.toString());
		if (msg != null) {
			if(msg.getGroupId() != null){ // 显示群聊提示
				holder.groupContainer.setVisibility(View.VISIBLE);
				holder.groupname.setText(msg.getGroupName());
			} else{
				holder.groupContainer.setVisibility(View.GONE);
			}
//			GetOneFriendData(msg.getFrom(),position,msg);
			if (mDataList.get(position)==null){
				holder.reason.setText(msg.getReason());
				holder.name.setText(msg.getNick());
			}else {
				holder.reason.setText(mDataList.get(position).getReason());
				holder.name.setText(mDataList.get(position).getNick());
			}


//			 holder.time.setText(DateUtils.getTimestampString(new
//			 Date(msg.getTime())));
			if (msg.getStatus() == InviteMesageStatus.BEAGREED) {
				holder.status.setVisibility(View.INVISIBLE);
				holder.status2.setVisibility(View.GONE);
				holder.reason.setText(str1);
			} else if(msg.getStatus() == InviteMesageStatus.BEREFUSED){
				holder.status.setVisibility(View.INVISIBLE);
				holder.status2.setVisibility(View.GONE);
				holder.reason.setText(str7);
			}else if (msg.getStatus() == InviteMesageStatus.BEINVITEED || msg.getStatus() == InviteMesageStatus.BEAPPLYED) {
				holder.status.setVisibility(View.VISIBLE);
				holder.status.setEnabled(true);
//				holder.status.setBackgroundResource(android.R.drawable.btn_default);
//				holder.status2.setBackgroundResource(android.R.drawable.btn_default);
				holder.status.setText(str2);
				if(msg.getStatus() == InviteMesageStatus.BEINVITEED){
					if (msg.getReason() == null) {
						// 如果没写理由
						holder.reason.setText(str3);
					}
				}else{ //入群申请
					if (TextUtils.isEmpty(msg.getReason())) {
						holder.reason.setText(str4 + msg.getGroupName());
					}
				}
				// 设置点击事件
				holder.status.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 同意别人发的好友请求
						acceptInvitation(holder.status,holder.status2, msg);
//						AgreeAddFriends(holder.status, holder.status2,msg);
					}
				});
				holder.status2.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 拒绝别人发的好友请求
						refuseInvitation(holder.status, holder.status2, msg);
					}
				});


			} else if (msg.getStatus() == InviteMesageStatus.AGREED) {
				holder.status.setText(str5);
				holder.status.setBackgroundDrawable(null);
				holder.status.setEnabled(false);
				holder.status2.setVisibility(View.GONE);
			} else if(msg.getStatus() == InviteMesageStatus.REFUSED){
				holder.status.setText(str6);
				holder.status.setBackgroundDrawable(null);
				holder.status.setEnabled(false);
				holder.status2.setVisibility(View.GONE);
			}

			// 设置用户头像
			String ImgURL = Constant.ImageHost_Small+msg.getUser().getAvatarid();
			Glide.with(context).load(ImgURL).into(holder.avator);
//			EaseUserUtils.setUserAvatar(getContext(), msg.getFrom(), holder.avator);
		}

		return convertView;
	}

	/**
	 * 同意好友请求或者群申请
	 * 
	 * @param button
	 * @param username
	 */
	private void acceptInvitation(final Button button,final Button button2, final InviteMessage msg) {

//		sjtAcceptInvitation(button, button2, msg);//sjt添加好友接口
		AgreeAddFriends(button,button2,msg);

	}


	private void emAcceptInvitation(final Button button,final Button button2, final InviteMessage msg) {
		final ProgressDialog pd = new ProgressDialog(context);
		String str1 = context.getResources().getString(R.string.Are_agree_with);
		final String str2 = context.getResources().getString(R.string.Has_agreed_to);
		final String str3 = context.getResources().getString(R.string.Agree_with_failure);
		pd.setMessage(str1);
		pd.setCanceledOnTouchOutside(false);
		pd.show();

		new Thread(new Runnable() {
			public void run() {
				// 调用sdk的同意方法
				try {
//					if(msg.getGroupId() == null) {//同意好友请求
//						EMChatManager.getInstance().acceptInvitation(msg.getFrom());
//					} else { //同意加群申请
//						EMGroupManager.getInstance().acceptApplication(msg.getFrom(), msg.getGroupId());
//					}
					msg.setStatus(InviteMesageStatus.AGREED);
					// 更新db
					ContentValues values = new ContentValues();
					values.put(InviteMessgeDao.COLUMN_NAME_STATUS, msg.getStatus().ordinal());
					messgeDao.updateMessage(msg.getId(), values);
					SjtHelper.getInstance().asyncFetchContactsFromServer(null);
					((Activity) context).runOnUiThread(new Runnable() {

						@Override
						public void run() {
							pd.dismiss();
							button.setText(str2);
							button.setBackgroundDrawable(null);
							button.setEnabled(false);
							button2.setVisibility(View.GONE);


						}
					});
				} catch (final Exception e) {
					((Activity) context).runOnUiThread(new Runnable() {

						@Override
						public void run() {
							pd.dismiss();
							Toast.makeText(context, str3 + e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					});

				}
			}
		}).start();
	}

	/**
	 * 拒绝好友请求或者群申请
	 *
	 * @param button
	 * @param username
	 */
	private void refuseInvitation(final Button button,final Button button2, final InviteMessage msg) {
		final ProgressDialog pd = new ProgressDialog(context);
		String str1 = context.getResources().getString(R.string.error_refuse_in);
		final String str2 = context.getResources().getString(R.string.error_refuse_yes);
		final String str3 = context.getResources().getString(R.string.error_refuse_no);
		pd.setMessage(str1);
		pd.setCanceledOnTouchOutside(false);
		pd.show();

		new Thread(new Runnable() {
			public void run() {
				// 调用sdk的拒绝方法
				try {
					if(msg.getGroupId() == null) {//拒绝好友请求
						EMChatManager.getInstance().refuseInvitation(msg.getFrom());
					}
					msg.setStatus(InviteMesageStatus.REFUSED);
					// 更新db
					ContentValues values = new ContentValues();
					values.put(InviteMessgeDao.COLUMN_NAME_STATUS, msg.getStatus().ordinal());
					messgeDao.updateMessage(msg.getId(), values);
					messgeDao.deleteMessage(msg.getFrom());
					Getusernames();//更新好友列表
					((Activity) context).runOnUiThread(new Runnable() {

						@Override
						public void run() {
							pd.dismiss();
							button.setText(str2);
							button.setBackgroundDrawable(null);
							button.setEnabled(false);
							button2.setVisibility(View.GONE);
							TipUtil.showToast(str2, context, 1);

						}
					});
				} catch (final Exception e) {
					((Activity) context).runOnUiThread(new Runnable() {

						@Override
						public void run() {
							pd.dismiss();
							Toast.makeText(context, str3 + e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					});

				}
			}
		}).start();
	}

	private static class ViewHolder {
		ImageView avator;
		TextView name;
		TextView reason;
		Button status;
		Button status2;
		LinearLayout groupContainer;
		TextView groupname;
		// TextView time;
	}



	//同意添加好友
	private void AgreeAddFriends(final Button button,final Button button2, final InviteMessage msg) {
		//显示Progress Dialog
		TipUtil.openProgressDialog(Constant.APPLICATION_NAME, context.getResources().getString(R.string.error_please_waitting), context);
		StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.AddFriend, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
					TipUtil.log("同意添加好友接口接口成功返回", response.toString(), 1);
					JSONTokener jsonParser = new JSONTokener(response);
					JSONObject res = (JSONObject) jsonParser.nextValue();
					String code = res.getString("code");
					String message = res.getString("message");
					if (code.equals("200")) {//成功
						TipUtil.closeProgressDialog();
						emAcceptInvitation(button, button2, msg);
						TipUtil.showToast(context.getResources().getString(R.string.error_add_firiend_success), context, 1);
					} else {//失败
						TipUtil.showToast(message, context, 1);
					}
				} catch (JSONException ex) {
					ex.printStackTrace();
					TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
				}
				TipUtil.closeProgressDialog();

			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				TipUtil.showToast(context.getResources().getString(R.string.error_network), context, 1);
				TipUtil.closeProgressDialog();
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
				String userId = mainSharedPreferences.getString("userId", "");
//				String mobile = mainSharedPreferences.getString("mobile", "");
				map.put("loginId", userId);
				map.put("userId",userId);
//				Log.e("userId", userId);
//				Log.e("friendId",msg.getFrom());
				map.put("friendId", msg.getFrom());
//				map.put("mobile", mobile);
				return map;

			}

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
				String cookie = mainSharedPreferences.getString("cookie", "");
				String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
				HashMap localHashMap = new HashMap();
				String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
				localHashMap.put("Cookie", cookieValue);
				return localHashMap;
			}
		};
		mQueue.add(stringRequest);
	}



	/**
	 * 获取好友
	 * @param Getusernames
	 */
	public void Getusernames() throws Exception{
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, context.getResources().getString(R.string.error_please_waitting), context);
		final List<String> usernames = new ArrayList<String>();
		final Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
		StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.GetFriendList, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
					TipUtil.closeProgressDialog();
					TipUtil.log("获取好友列表", response.toString(), 1);
					JSONTokener jsonParser = new JSONTokener(response);
					JSONObject res = (JSONObject) jsonParser.nextValue();
					String code = res.getString("code");
					String message = res.getString("message");
					JSONObject Data=res.getJSONObject("data");
					if (code.equals("200")) {//成功
						JSONArray friendList = Data.getJSONArray("friendList");
						for (int i = 0; i < friendList.length(); i++) {
							JSONObject aData = (JSONObject) friendList.get(i);
							String userId  = aData.getString("userId");
							String nick = aData.getString("nickName");
							String initialLetter = aData.getString("initialLetter");
							String mobile = aData.getString("mobile");
							String imageId = aData.getString("imageId");
							String imageUrl = aData.getString("imageUrl");
							EaseUser user = new EaseUser(userId);
							user.setNick(nick);
							user.setMobile(mobile);
							user.setInitialLetter(initialLetter);
							user.setAvatarid(imageId);
							user.setAvatar(imageUrl);
							EaseCommonUtils.setUserInitialLetter(user);

							userlist.put(userId, user);
//                                           usernames.add(userId);
							usernames.add(i,userId);

						}
						SjtHelper.getInstance().getContactList().clear();
						SjtHelper.getInstance().getContactList().putAll(userlist);
						// 存入db
						UserDao dao = new UserDao(context);
						List<EaseUser> users = new ArrayList<EaseUser>(userlist.values());
						dao.saveContactList(users);
					} else {//失败
//						TipUtil.log(message, response.toString(), 1);
//						SjtModel.class.setContactSynced(false);
////
					}
				} catch (Exception ex) {
					ex.printStackTrace();
//					TipUtil.log(appContext.getResources().getString(R.string.error_service), response.toString(), 1);


				}
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
//                TipUtil.log(appContext.getResources().getString(R.string.error_network),response.toString() , 1);
//                TipUtil.closeProgressDialog();
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				SharedPreferences mainSharedPreferences =context. getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
				String userId = mainSharedPreferences.getString("userId", "");
				map.put("loginId", userId);

				return map;
			}
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				SharedPreferences mainSharedPreferences =context. getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
				String cookie = mainSharedPreferences.getString("cookie", "");
				String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
				HashMap localHashMap = new HashMap();
				String cookieValue = cookie + ";" + rememberMeValue;
				localHashMap.put("Cookie", cookieValue);
				return localHashMap;
			}
		};
		mQueue.add(stringRequest);
	}

}
